﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DIProject.Dictionary
{
    public partial class GoodsDetails : Form
    {
        private string  _buffer;

        public string  Buffer
        {
            get { return _buffer; }
            set { _buffer = value; }
        }

        #region кеш формы
        private static DIProject.Dictionary.GoodsDetails _goodsDetailsCache = null;

        public static DIProject.Dictionary.GoodsDetails GoodsDetailsCache
        {
            get
            {
                return _goodsDetailsCache;
            }
            set
            {
                _goodsDetailsCache = value;
            }
        }           
        #endregion
        private Util.ActionType _actTypemyVar;

        public Util.ActionType OpenAction
        {
            get { return _actTypemyVar; }
            set { _actTypemyVar = value; }
        }
        private DataSets.Dictionary.GoodsDataTable _data;

        public DataSets.Dictionary.GoodsDataTable Data
        {
            get { return _data; }
            set { _data = value; }
        }
        private DataSets.Dictionary.GoodsRow _curRow;

        public DataSets.Dictionary.GoodsRow CurrentRow
        {
            get { return _curRow; }
            set { _curRow = value; }
        }
        private Int32  _curId;

        public Int32  CurrentId
        {
            get { return _curId; }
            set { _curId = value; }
        }
        Int32? parentId = null;
        private bool _isDivGood;
        /// <summary>
        /// показывает, создаем новый или делим старый.
        /// </summary>
        public bool IsDivGood
        {
            get { return _isDivGood; }
            set { _isDivGood = value; }
        }

        public GoodsDetails(Util.ActionType actType, DataSets.Dictionary.GoodsDataTable data, Int32 currentId)
        {
            InitializeComponent();
            this.Data = data;
            this.OpenAction = actType;
            this.CurrentId = currentId;
            if (currentId != null)
                this.CurrentRow = this.Data.FindById(this.CurrentId);
            this.EnableInit(false);
           
        }
        private void EnableInit(bool isDiv)
        {
            ///если делим товар
            if (isDiv)
            {
                switch (this.OpenAction)
                {
                    case DIProject.Util.ActionType.Insert:
                        this.EnabbleDivInsert();
                        break;
                    case DIProject.Util.ActionType.Update:
                        this.EnableDivUpdate();
                        break;
                    default:
                        break;
                }
            }
                ///если не делим
            else
            {
                switch (this.OpenAction)
                {
                    case DIProject.Util.ActionType.Insert:
                        this.EnableNewInsert();
                        break;
                    case DIProject.Util.ActionType.Update:
                        this.EnableNewUpdate();
                        break;
                    default:
                        break;
                }
            }
        }
        public GoodsDetails(Util.ActionType actType, DataSets.Dictionary.GoodsDataTable data, Int32 currentId,bool isDiv)
        {
            InitializeComponent();
            this.Data = data;
            this.OpenAction = actType;
            this.CurrentId = currentId;
            this.IsDivGood = isDiv;
            if (currentId != null)
                this.CurrentRow = this.Data.FindById(this.CurrentId);
            this.EnableInit(this.IsDivGood);
        }

        private void GoodsDetails_Load(object sender, EventArgs e)
        {
            
            lock (this)
            {
                this.Cursor = Cursors.WaitCursor;
                InitComboBoxes();
                switch (this.OpenAction)
                {
                    case DIProject.Util.ActionType.Insert:
                        InitInsert();
                        break;
                    case DIProject.Util.ActionType.Update:
                        InitUpdate();
                        break;
                    default:
                        this.Hide();
                        break;
                }
                this.Cursor = Cursors.Default;
            }
            this.EnableInit(this.IsDivGood);
        }

       
        private void InitComboBoxes()
        {
            cbAssortment.DataSource = DIProject.Data.Assortment.Data;
            cbCountry.DataSource = DIProject.Data.Country.Data;
            cbManufacturer.DataSource = new DIProject.Data.Test2().Data;
          //  cbParentId.DataSource = DIProject.Data.Goods.Data;
        }
        public void MyShow(Util.ActionType actType, DataSets.Dictionary.GoodsDataTable data, Int32 id)
        {
            this.OpenAction = actType;
            this.Data = data;
            this.CurrentId = id;
            this.CurrentRow = this.Data.FindById(this.CurrentId);
            switch (this.OpenAction)
            {
                case DIProject.Util.ActionType.Insert:
                    InitInsert();
                    break;
                case DIProject.Util.ActionType.Update:
                    this.InitUpdate();
                    break;
            }
            this.Show();
            this.EnableInit(false);
        }
        public void MyShow(Util.ActionType actType, DataSets.Dictionary.GoodsDataTable data, Int32 id,bool isDivGood)
        {
            this.OpenAction = actType;
            this.Data = data;
            this.CurrentId = id;
            this.CurrentRow = this.Data.FindById(this.CurrentId);
            this.IsDivGood = isDivGood;
            switch (this.OpenAction)
            {
                case DIProject.Util.ActionType.Insert:
                    InitInsert();
                    break;
                case DIProject.Util.ActionType.Update:
                    this.InitUpdate();
                    break;
            }
            this.Show();
            this.EnableInit(this.IsDivGood);
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void btnInsertUpdate_Click(object sender, EventArgs e)
        {
            switch (this.OpenAction)
            {
                case DIProject.Util.ActionType.Insert:
                    this.Insert();
                    break;
                case DIProject.Util.ActionType.Update:
                    this.Update1();
                    break;
                default: break;
            }
            this.Hide();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            this.Delete();
        }
        private void GoodsDetails_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;
                this.Hide();
            }
        }
        #region операции со строками
        /// <summary>
        /// Удаление записи
        /// </summary>
        private void Delete()
        {
            if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
                return;
            string _mW;
            if (DIProject.Data.Sync.IsAdmin)
            {
                _mW = "PhysicallyDelete";
            }
            else
            {
                _mW = FirstForm.Login;
            }
            try
            {
                DataSets.DictionaryTableAdapters.GoodsTableAdapter adapter = new DIProject.DataSets.DictionaryTableAdapters.GoodsTableAdapter();
                CurrentRow.MW = _mW;
                CurrentRow.Delete();
                adapter.Update(this.Data);
                this.Data.AcceptChanges();
                this.Hide();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void Insert()
        {
            this.CurrentRow = this.Data.NewGoodsRow();
            this.CurrentRow.AssortmentId = (Int32)cbAssortment.SelectedValue;
            this.CurrentRow.ManufacturerId = (Int32)cbManufacturer.SelectedValue;
            this.CurrentRow.CountryId = (Int32)cbCountry.SelectedValue;
            if (IsDivGood)
                this.CurrentRow.ChildId = (Int32)cbParentId.SelectedValue;
            this.CurrentRow.AllowUnPack = cbxAllowUnPack.Checked;
            this.CurrentRow.RetailPack = Convert.ToInt32(txbRetailPack.Text);
            this.CurrentRow.WholesalePack = Convert.ToInt32(txbWholesalePack.Text);
            this.CurrentRow.ManufactureBarCode = txbManufactureBarCode.Text;
            if(!string.IsNullOrEmpty(this.txbFixedPrice.Text))
                this.CurrentRow.FixedPrice = Convert.ToDecimal(this.txbFixedPrice.Text);
            if (!string.IsNullOrEmpty(this.txbNote.Text))
                this.CurrentRow.Note = this.txbNote.Text;
            this.CurrentRow.MD = DateTime.Now;
            this.CurrentRow.MW = FirstForm.Login;
            this.CurrentRow.ToDelete = false;
            this.CurrentRow.DefekturaAggregate = cbAgregate.Checked;
            this.Data.Rows.Add(this.CurrentRow);
            DataSets.DictionaryTableAdapters.GoodsTableAdapter adapter = new DIProject.DataSets.DictionaryTableAdapters.GoodsTableAdapter();
            adapter.Update(this.Data);
            DataSets.DictionaryTableAdapters.LastGodsTableAdapter adap = new DIProject.DataSets.DictionaryTableAdapters.LastGodsTableAdapter();
            DataSets.Dictionary.LastGodsDataTable tab = adap.GetData();
            DataSets.Dictionary.LastGodsRow lRow = tab.Rows[0] as DataSets.Dictionary.LastGodsRow;
            this.CurrentRow.ManufactureName = lRow.ManufactureName;
            this.CurrentRow.Name = lRow.Name;
            this.CurrentRow.CountryName = lRow.CountryName;
            this.CurrentRow.Original_MD = this.CurrentRow.MD;
            this.CurrentRow.Original_Id = this.CurrentRow.Id;
            this.Data.AcceptChanges();
            this.Hide();
        }
        private void Update1()
        {
            this.CurrentRow.AssortmentId = (Int32)cbAssortment.SelectedValue;
            this.CurrentRow.ManufacturerId = (Int32)cbManufacturer.SelectedValue;
            this.CurrentRow.CountryId = (Int32)cbCountry.SelectedValue;
            // this.CurrentRow.ParentId = 1;
            this.CurrentRow.AllowUnPack = cbxAllowUnPack.Checked;
            this.CurrentRow.RetailPack = Convert.ToInt32(txbRetailPack.Text);
            this.CurrentRow.WholesalePack = Convert.ToInt32(txbWholesalePack.Text);
            this.CurrentRow.ManufactureBarCode = txbManufactureBarCode.Text;
            if (!string.IsNullOrEmpty(this.txbFixedPrice.Text))
                this.CurrentRow.FixedPrice = Convert.ToDecimal(this.txbFixedPrice.Text);
            if (!string.IsNullOrEmpty(this.txbNote.Text))
                this.CurrentRow.Note = this.txbNote.Text;
            this.CurrentRow.MD = DateTime.Now;
            this.CurrentRow.MW = FirstForm.Login;
            this.CurrentRow.ToDelete = false;
            this.CurrentRow.DefekturaAggregate = cbAgregate.Checked;
            DataSets.DictionaryTableAdapters.GoodsTableAdapter adapter = new DIProject.DataSets.DictionaryTableAdapters.GoodsTableAdapter();
            adapter.Update(this.Data);
            this.CurrentRow.Original_MD = this.CurrentRow.MD;
            this.CurrentRow.Original_Id = this.CurrentRow.Id;
            this.Data.AcceptChanges();
            this.Hide();
        }
       
        private void CommonInit()
        {
            cbAssortment.SelectedValue = this.CurrentRow.AssortmentId;
            cbCountry.SelectedValue = this.CurrentRow.CountryId;
            cbManufacturer.SelectedValue = this.CurrentRow.ManufacturerId;
            this.parentId = DIProject.Data.Goods.GetParentId(this.CurrentId);
            if (parentId.HasValue)
            {
                cbParentId.SelectedValue = parentId.Value;
            }            
            txbWholesalePack.Text = this.CurrentRow.WholesalePack.ToString();
            if (!this.CurrentRow.IsManufactureBarCodeNull())
                txbManufactureBarCode.Text = this.CurrentRow.ManufactureBarCode;
            txbRetailPack.Text = this.CurrentRow.RetailPack.ToString();
            if (!this.CurrentRow.IsFixedPriceNull())
                txbFixedPrice.Text = this.CurrentRow.FixedPrice.ToString();
            cbxAllowUnPack.Checked = this.CurrentRow.AllowUnPack;
            if (!this.CurrentRow.IsNoteNull())
                txbNote.Text = this.CurrentRow.Note;
        }
        private void InitInsert()
        {
            btnInsertUpdate.Text = "Сохранить";
            btnDelete.Visible = false;
            cbParentId.Enabled = false;
        }
        private void InitUpdate()
        {
            CommonInit();
            btnInsertUpdate.Text = "Изменить";
            btnDelete.Visible = true;
            cbParentId.Enabled = true;
        }
        #endregion
        private void txbWholesalePack_Validating(object sender, CancelEventArgs e)
        {
            e.Cancel = !Util.Validator.Int32Validation(txbWholesalePack, string.Empty);
        }
        private void txbRetailPack_Validating(object sender, CancelEventArgs e)
        {
            e.Cancel = !Util.Validator.Int32Validation(txbRetailPack, string.Empty);
        }

        private void txbFixedPrice_Validating(object sender, CancelEventArgs e)
        {
            if (string.IsNullOrEmpty(txbFixedPrice.Text))
                return;
            e.Cancel = !Util.Validator.DecimalValidation(txbFixedPrice, string.Empty);
        }
        #region Enable-Disable Controls
        /// <summary>
        /// нет ассортимента, есть родительский
        /// </summary>
        private void EnabbleDivInsert()
        {
            this.cbAssortment.Enabled = false;
            this.cbCountry.Enabled = false;
            this.cbManufacturer.Enabled = false;
            this.cbParentId.Enabled = true;
            this.cbxAllowUnPack.Enabled = true;
            this.txbFixedPrice.Enabled = false;
            this.txbManufactureBarCode.Enabled = false;
            this.txbNote.Enabled = true;
            this.txbRetailPack.Enabled = true;
            this.txbWholesalePack.Enabled = false;
        }
        private void EnableNewInsert()
        {
            this.cbAssortment.Enabled = true;
            this.cbCountry.Enabled = true;
            this.cbManufacturer.Enabled = true;
            this.cbParentId.Enabled = false;
            this.cbxAllowUnPack.Enabled = true;
            this.txbFixedPrice.Enabled = true;
            this.txbManufactureBarCode.Enabled = true;
            this.txbNote.Enabled = true;
            this.txbRetailPack.Enabled = true;
            this.txbWholesalePack.Enabled = true;
        }
        private void EnableDivUpdate()
        {
            this.cbAssortment.Enabled = false;
            this.cbCountry.Enabled = false;
            this.cbManufacturer.Enabled = false;
            this.cbParentId.Enabled = true;
            this.cbxAllowUnPack.Enabled = true;
            this.txbFixedPrice.Enabled = false;
            this.txbManufactureBarCode.Enabled = false;
            this.txbNote.Enabled = true;
            this.txbRetailPack.Enabled = true;
            this.txbWholesalePack.Enabled = false;
        }
        /// <summary>
        /// нет родительского товара
        /// </summary>
        private void EnableNewUpdate()
        {
            this.cbAssortment.Enabled = true;
            this.cbCountry.Enabled = true;
            this.cbManufacturer.Enabled = true;
            this.cbParentId.Enabled = false;
            this.cbxAllowUnPack.Enabled = true;
            this.txbFixedPrice.Enabled = true; ;
            this.txbManufactureBarCode.Enabled = true;
            this.txbNote.Enabled = true;
            this.txbRetailPack.Enabled = true;
            this.txbWholesalePack.Enabled = true;
        }

        #endregion
        /// <summary>
        /// при разделении меняем остальные 3 комбобокса
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbParentId_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!this.IsDivGood)
                return;
            lblIdPId.Text = cbParentId.SelectedValue.ToString();
            DataRowView o = cbParentId.SelectedItem as DataRowView;
            DataSets.Dictionary.vwGoodsDetailedRow gdr = o.Row as DataSets.Dictionary.vwGoodsDetailedRow;
            DataSets.Dictionary.GoodsRow gr = this.Data.FindById(gdr.Id);
            if (gr != null)
            {
                cbAssortment.SelectedValue = gr.AssortmentId;
                cbManufacturer.SelectedValue = gr.ManufacturerId;
                cbCountry.SelectedValue = gr.CountryId;
                if (!gr.IsManufactureBarCodeNull())
                {
                    txbManufactureBarCode.Text = gr.ManufactureBarCode;
                }
                txbWholesalePack.Text = gr.WholesalePack.ToString();
                txbRetailPack.Text = gr.RetailPack.ToString();
                if (!gr.IsFixedPriceNull())
                {
                    txbFixedPrice.Text = gr.FixedPrice.ToString();
                }
                cbxAllowUnPack.Checked = false;
                if (!gr.IsNoteNull())
                {
                    txbNote.Text = gr.Note;
                }
            }
        }
    }
}